<?php
global $oper;
$oper = new operation;
class operation
{
	private $msg;
	private $result;
	private function execTime()
	{
		$time = explode(" ", microtime());
		$usec = (double)$time[0];
		$sec = (double)$time[1];
		return $sec + $usec;
	}
	private function totalfile($path)
	{
		$rn = 0;
		$dir = dir($path);
		while($file = $dir->read())
		{		
			$ext = explode('.',$file);
			if($ext[1] == 'cache')
				$rn++; 
		}
		
		return $rn;
	}
	private function floorTime($seconds)
    {
        $times = '';
        $days = floor(($seconds/86400)%30);
        $hours = floor(($seconds/3600)%24);
        $minutes = floor(($seconds/60)%60);
        $seconds = floor($seconds%60);
        if($seconds >= 1) $times .= $seconds.'秒';
        if($minutes >= 1) $times = $minutes.'分钟 '.$times;
        if($hours >= 1) $times = $hours.'小时 '.$times;
        if($days >= 1)  $times = $days.'天';
        if($days > 30) return false;
        $times .= '前';
        return str_replace(" ", '', $times);
    }	
	private function jsonString($str)
	{
		return preg_replace("/([\\\\\/'])/",'\\\$1',$str);
	}
	function showmsg($msg, $gourl, $onlymsg=0, $limittime=0)
	{
		$htmlhead  = "<html>\r\n<head>\r\n<title>操作提示信息</title>\r\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\r\n";
		$htmlhead .= "<base target='_self'/>\r\n<style>div{line-height:160%;}</style></head>\r\n<body style='margin:0;background:#fff'>\r\n<center style=\"font:400 12px/20px '';color:#15428B\">\r\n";
		$htmlfoot  = "\r\n</center>\r\n</body>\r\n</html>\r\n";
		$litime = ($limittime==0 ? 1000 : $limittime);
		$func = '';
		if($gourl=='-1')
		{
			if($limittime==0) $litime = 5000;
			$gourl = "<script>javascript:history.go(-1);</script>";
		}
		else if($gourl == '0')
		{
			$gourl = '';
			$rmsg = $msg;
		}
		else if($gourl=='' || $onlymsg==1)
		{
			$rmsg = "<script>alert(\"".str_replace("\"","“",$msg)."\");</script>";
		}
		else
		{
			if(preg_match('/close::/',$gourl))
			{
				$tgobj = trim(preg_replace('/close::/', '', $gourl));
				$gourl = 'javascript:;';
				$func .= "window.parent.document.getElementById('{$tgobj}').style.display='none';\r\n";
			}
			$rmsg = '<script>';
			$func .= "      var pgo=0;
		  function gourl(){
			if(pgo==0){ location='$gourl'; pgo=1; }
		  }\r\n";
			$rmsg .= $func;			
			$rmsg .= "document.write(\"".str_replace("\"","“",$msg)."\");\r\n";
			$rmsg .= "document.write(\"";			
			if($onlymsg==0)
			{
				if( $gourl != 'javascript:;' && $gourl != '')
				{
					$rmsg .= "<br /><a href='{$gourl}' style='color:#f00'>如果你的浏览器没反应，请点击这里...</a>";
					$rmsg .= "\");\r\n";
					$rmsg .= "setTimeout('gourl()',$litime);";
				}
				else
				{
					$rmsg .= "\");\r\n";
				}
			}
			else
			{
				$rmsg .= "\");\r\n";
			}
			$rmsg .= '</script>';
		}
		$msg  = $htmlhead.$rmsg.$htmlfoot;
		echo $msg;
	}
	private function formatBytes($bytes) 
	{
		if($bytes >= 1073741824) 
		{
			$bytes = round($bytes / 1073741824 * 100) / 100 . 'GB';
		} elseif($bytes >= 1048576) 
		{
			$bytes = round($bytes / 1048576 * 100) / 100 . 'MB';
		} elseif($bytes >= 1024) 
		{
			$bytes = round($bytes / 1024 * 100) / 100 . 'KB';
		} else 
		{
			$bytes = $bytes . 'Bytes';
		}
		return $bytes;
	}
	function saveRemoteImg($url)
	{	
		global $ext,$max;	
		$ext = '('.str_replace(',','|',$ext).')';	
		if(substr($url,0,10) == 'data:image')
		{	
			if(!preg_match('/^data:image\/'.$ext.'/i',$url,$ext))
				return false;	
			$ext = $ext[1];	
			$img = base64_decode(substr($url,strpos($sUrl,'base64,') + 7));	
		}	
		else
		{	
			if(!preg_match('/\.'.$ext.'$/i',$url,$ext))
				return false;	
			$ext = $ext[1];	
			$img = $this->GetUrl($url);	
		}	
		if(strlen($img)>$max)
			return false;
		$file = $this->GetPath($ext);	
		file_put_contents($file,$img);	
		$fileinfo = @getimagesize($file);	
		if(!$fileinfo||!preg_match("/image\/".$ext."/i",$fileinfo['mime']))
		{	
			@unlink($file);	
			return false;	
		}	
		return $file;
	}
	function GetUrl($url,$num=0)
	{	
		$arrUrl = parse_url(trim($url));
		if(!$arrUrl)
			return false;	
		$host = $arrUrl['host'];	
		$port = isset($arrUrl['port'])?$arrUrl['port']:80;	
		$path = $arrUrl['path'].(isset($arrUrl['query'])?"?".$arrUrl['query']:"");	
		$fp = @fsockopen($host,$port,$errno, $errstr, 30);	
		if(!$fp)
			return false;	
		$output="GET $path HTTP/1.0\r\nHost: $host\r\nReferer: $url\r\nConnection: close\r\n\r\n";	
		stream_set_timeout($fp, 60);	
		@fputs($fp,$output);	
		$Content='';	
		while(!feof($fp))	
		{	
			$buffer = fgets($fp, 4096);	
			$info = stream_get_meta_data($fp);	
			if($info['timed_out'])
				return false;	
			$Content .= $buffer;	
		}	
		@fclose($fp);	
		global $jumpCount;
		if(preg_match("/^HTTP\/\d.\d (301|302)/is",$Content)&&$num < 5)	
		{	
			if(preg_match("/Location:(.*?)\r\n/is",$Content,$murl))
				return $this->getUrl($murl[1],$num+1);	
		}	
		if(!preg_match("/^HTTP\/\d.\d 200/is", $Content))
			return false;	
		$Content = explode("\r\n\r\n",$Content,2);	
		$Content = $Content[1];	
		if($Content)
			return $Content;	
		else 
			return false;
	}
	function GetPath($ext)
	{	
		global $dirType,$attachDir;
			switch($dirType)	
			{	
			case 1: $attachSubDir = 'day_'.date('ymd'); break;	
			case 2: $attachSubDir = 'month_'.date('ym'); break;	
			case 3: $attachSubDir = 'ext_'.$sExt; break;	
			}	
			$newAttachDir = $attachDir.'/'.$attachSubDir;	
			if(!is_dir($newAttachDir))	
			{	
				@mkdir($newAttachDir, 0777);	
				@fclose(fopen($newAttachDir.'/index.htm', 'w'));	
			}		
		$newFilename=date("YmdHis").mt_rand(1000,9999).'.'.$sExt;	
		$targetPath = $newAttachDir.'/'.$newFilename;	
		return $targetPath;
	}
	private function GetField($tab,$field,$key)
	{
		global $dbo;
		$rn = '';
		$sql = "select " .$field. " from `@db__" .$tab."` where title='" .$key. "'";
		$rn = $dbo->single($sql);
		$rn = $rn[$field];
		return $rn;
	}
	private function GetModule($type)
	{
		$rn = '';
		switch($type)
		{
			case 'guide':$rn = '评测导购';break;
			case 'promotion':$rn = '特品特惠';break;			
			case 'activity':$rn = '热门推荐';break;
			case 'coupon':$rn = '发现发券';break;
			case 'single':$rn = '单页信息';break;
			case 'seo':$rn = 'SEO信息';break;
			case 'flink':$rn = '友情链接';break;
			case 'adv':$rn = '广告图片';break;
			case 'member':$rn = '注册用户';break;
			case 'comment':$rn = '评论信息';break;
			case 'catalog':$rn = '频道节点';break;		
			case 'payment':$rn = '订单信息';break;		
			case 'hotkey':$rn = '热门标题';break;
		}
		return '<font color=red><strong>'.$rn.'</strong></font>';
	}
	function ajaxTodo($ids)
	{
		global $tpl;
		$rn = '';
		if(empty($ids))
			$rn .= '["0","请选择所属栏目"]';
		else
		{
			$rn .= '["0","顶层栏目"]';
			$data = $tpl->GetInfoList('catalog',0,"type='".$ids."' and cid=0",'pid','asc');
			foreach($data as $k => $v)
			{
				$rn .= empty($rn)?'["'.$v['id'].'", "'.$v['title'].'"]':',["'.$v['id'].'", "'.$v['title'].'"]';
			}
		}
		echo '['.$rn.']';
	}
	function sysConfig($data,$tabid)
	{
		$data = serialize($data);
		file_put_contents('../config/kp.'.$tabid.'.config',$data);
		$this->msg['statusCode'] = '200';
		$this->msg['message'] = '系统参数配置成功';
		$this->msg['navTabId'] = $tabid;
		$this->msg['rel'] = '';
		$this->msg['callbackType'] = '';
		$this->msg['url'] = '';
		echo json_encode($this->msg);	
	}
	
	function addInfo($tab,$data,$sk = '')
	{
		global $dbo;
		$callback = '';
		if($tab != 'seo' && $tab !='single')
			$callback = 'closeCurrent';
		if($tab == 'admin')
			$data['password'] = md5($data['password']);		
		$this->result = $dbo->insert($tab,$data);
		if($this->result > 0)
		{
			$this->msg['statusCode'] = 200;
			$this->msg['message'] = $this->GetModule($tab).'信息添加成功';
			$this->msg['navTabId'] = $tab;
			$this->msg['callbackType'] = $callback;
		}
		else
		{
			$this->msg['statusCode'] = 300;
			$this->msg['message'] = $this->GetModule($tab).'信息添加失败' ;
			$this->msg['navTabId'] = $tab;
			$this->msg['callbackType'] = $callback;
		}
		$this->msg['rel'] = '';
		$this->msg['url'] = '';
		if($sk == '')
			echo json_encode($this->msg);
	}
	function editInfo($tab,$data,$ids,$sk = '')
	{
		global $dbo;
		$callback = '';
		$op = '';
		if($tab != 'seo' && $tab !='single')
			$callback = 'closeCurrent';
		if($tab == 'admin')
		{
			if(empty($data['password']))
				unset($data['password']);
			else
				$data['password'] = md5($data['password']);
		}		
		if($tab == 'activity' ||  $tab == 'promotion' || $tab == 'coupon')
			$this->result = $dbo->modify($tab,$data,$data['pid']);	
		else
			$this->result = $dbo->update($tab,$data,$ids);
		
		if($tab == 'activity') 
			$op = 'goods';
		else if($tab == 'promotion') 
			$op = 'goods';
		else if($tab == 'coupon') 
			$op = 'goods';
		$this->msg['statusCode'] = 200;
		$this->msg['message'] = $this->GetModule($tab).'信息修改成功';
		$this->msg['navTabId'] = $op;
		$this->msg['callbackType'] = $callback;		
		$this->msg['rel'] = '';
		$this->msg['url'] = '';
		if($sk == '')
			echo json_encode($this->msg);
	}
	function saveInfo($tab,$data,$ids)
	{
		global $dbo;
		$sql = 'select count(id) as num from `@db__' .$tab. '` where id=' .$ids;
		$this->result = $dbo->single($sql);		
		if($this->result['num'] > 0)
			$this->editInfo($tab,$data,$ids);
		else
			$this->addInfo($tab,$data);
	}
	function updateInfo($tab,$data,$ids)
	{
		global $dbo;
		$sql = "select count(id) as num from `@db__" .$tab. "` where pid='" .$ids. "'";
		$this->result = $dbo->single($sql);		
		if($this->result['num'] > 0)
			$this->editInfo($tab,$data,$ids,'import');
		else
			$this->addInfo($tab,$data,'import');
	}
	private function insertInfo($tab,$data,$key)
	{
		global $dbo;
		$sql = "select count(id) as num from `@db__" .$tab. "` where title='" .$key. "'";
		$this->result = $dbo->single($sql);	
		if($this->result['num'] <= 0)
			$this->addInfo($tab,$data);
	}
	function purgeOption($tab,$ids,$type)
	{
		global $dbo;
		$op = '';
		if($type == 100)
		{
			$this->result = $dbo->clear('userinfo',$ids);	
			$this->result = $dbo->clear('findx',$ids);	
			$this->result = $dbo->clear('message',$ids);	
			$this->result = $dbo->clear('payment',$ids);	
			$this->result = $dbo->purge($tab,$ids,$type);	
		}
		else
		{
			$this->result = $dbo->purge($tab,$ids,$type);
		}
		if($tab == 'activity') 
			$op = 'goods';
		else if($tab == 'promotion') 
			$op = 'goods';
		else if($tab == 'coupon') 
			$op = 'goods';
		$this->msg['statusCode'] = 200;
		$this->msg['message'] = $this->GetModule($tab).'删除成功';
		$this->msg['navTabId'] = $op;
		$this->msg['callbackType'] = '';		
		$this->msg['rel'] = '';
		$this->msg['url'] = '';
		echo json_encode($this->msg);
	}
	function sortOption($tab,$pid,$ids)
	{
		global $dbo;
		$tp = $pid;
		$arr = array();
		$ids = explode(',',$ids);
		$pid = explode(',',$pid);
		foreach($ids as $k => $v)
		{
			$arr['pid'] = $pid[$k];
			$this->result = $dbo->update($tab,$arr,$v);
		}
		$this->msg['statusCode'] = 200;
		$this->msg['message'] = $this->GetModule($tab).'排序号更新成功'.$tp;
		$this->msg['navTabId'] = $tab;
		$this->msg['callbackType'] = '';		
		$this->msg['rel'] = '';
		$this->msg['url'] = '';
		echo json_encode($this->msg);
	}
	function examineOption($tab,$ids,$pos)
	{
		global $dbo;
		$op = '';
		$arr = array();
		$ids = explode(',',$ids);		
		foreach($ids as $k => $v)
		{
			$arr['fid'] = $pos;
			$arr['udatetimes'] = time();
			$this->result = $dbo->update($tab,$arr,$v);
		}
		if($tab == 'activity') 
			$op = 'goods';
		else if($tab == 'promotion') 
			$op = 'goods';
		else if($op == 'coupon') 
			$tab = 'goods';
		$this->msg['statusCode'] = 200;
		$this->msg['message'] = $this->GetModule($tab).'状态更新成功';
		$this->msg['navTabId'] = $op;
		$this->msg['callbackType'] = '';		
		$this->msg['rel'] = '';
		$this->msg['url'] = '';
		echo json_encode($this->msg);
	}
	function uploadForm($file,$field,$f)
	{
		$file = $file[$f];
		print_r($file);
		$ext = explode('.',$file['name']);
		$dir = date('Ym',time());
		if(!file_exists('../upload/litpic/'.$dir)) 
			mkdir('../upload/litpic/'.$dir); 
		$sfile = '/upload/litpic/'.$dir.'/'.date('YmdHis',time()).rand(100,999).'.'.$ext[count($ext)-1];
		echo move_uploaded_file($file['tmp_name'],'../'.$sfile);
		echo "<script>parent.upform.".$field.".value='".$sfile."'</script>";
	}
	function uploadEditor()
	{
		$inputName = 'filedata';
		$dir = '/upload/image';
		$maxsize = 2097152;
		$ext = 'jpg,jpeg,gif,png,bmp';
		$err = "";
		$msg = "''";
		$tempPath =  '..'.$dir.'/'.date("YmdHis").mt_rand(100,999).'.tmp';
		$localName='';
		if(isset($_SERVER['HTTP_CONTENT_DISPOSITION'])&&preg_match('/attachment;\s+name="(.+?)";\s+filename="(.+?)"/i',$_SERVER['HTTP_CONTENT_DISPOSITION'],$info))
		{
			file_put_contents($tempPath,file_get_contents("php://input"));
			$localName = urldecode($info[2]);
		}
		else
		{
			$upfile = @$_FILES[$inputName];
			if(!isset($upfile))
				$err = '文件域的name错误';
			elseif(!empty($upfile['error']))
				$err = '文件上传失败';
			elseif(empty($upfile['tmp_name']) || $upfile['tmp_name'] == 'none')
			$err = '无文件上传';
			else
			{
				move_uploaded_file($upfile['tmp_name'],$tempPath);
				$localName = $upfile['name'];
			}
		}
		if($err == '')
		{
			$fileInfo = pathinfo($localName);
			$extension = $fileInfo['extension'];
			if(preg_match('/^('.str_replace(',','|',$ext).')$/i',$extension))
			{
				$bytes = filesize($tempPath);
				if($bytes > $maxsize)$err='请不要上传大小超过'.formatBytes($maxAttachSize).'的文件';
				else
				{
					$attachSubDir = date('Ym',time());
					$dir = $dir.'/'.$attachSubDir;
					if(!is_dir('../'.$dir))
					{
						@mkdir('../'.$dir, 0777);
					}
					$newFilename = date("YmdHis").mt_rand(100,999).'.'.$extension;
					$targetPath = $dir.'/'.$newFilename;
					
					rename($tempPath,'..'.$targetPath);
					@chmod($targetPath,0755);
					$targetPath = $this->jsonString($targetPath);
					$msg = "'!$targetPath'";
					//else $msg="{'url':'".$targetPath."','localname':'".jsonString($localName)."','id':'".time()."'}";
				}
			}
			else $err = '上传文件扩展名必需为：'.$ext;
			@unlink($tempPath);
		}
		echo "{'err':'".$this->jsonString($err)."','msg':".$msg."}";
	}
	function uploadRemote($file)
	{/*
		arrUrls=explode('|',$file['urls']);
		$urlCount=count($arrUrls);
		for($i=0;$i<$urlCount;$i++)
		{	
		$localUrl=$this->saveRemoteImg($arrUrls[$i]);	
		//if($localUrl)
			$arrUrls[$i]=$localUrl;}
		echo implode('|',$arrUrls);*/
	}
	function importc($p)
	{
		$tp = "文件处理中,如果文件较大，可能会比较缓慢,请您耐心等待..";
		$this->showmsg($tp,'handle.php?m=imports&path='.$p['path'].'&psize='.$p['psize'],0,100);		
	}
	function imports($p)
	{
		$t1 = $this->execTime();
		$csv = new import;
		$psize = isset($p['psize']) ? $p['psize'] : 20;
		$csv = new import;
		$csv->path = $path = '../data/'.$p['path'];
		$csv->open();
		$total = $csv->total() - 1;
		for($m = 0;$m <= ceil($total / $psize) - 1;$m++)
		{
			$csv->get($psize - 1,(($m * $psize) + 1),($m + 1));
		}		
		$t2 = $this->execTime();
		$t2 = $t2 - $t1;	
		$tp = "<div style='width:200px;height:18px;border:1px solid #15428B;text-align:left'><div style='width:200px;height:18px;background:#2583c9'></div></div>";
		$tp = "<br/>本次用时：<b style='color:red'>".number_format($t2,2)."</b> 秒，总用时：<b style='color:red'>".number_format($t2,2)."</b> 秒，.文件加载成功：继续执行任务...";
		echo $this->showmsg($tp,'handle.php?m=importv&time='.$t2.'&len=0&f=1',0,100);
	}
	function importv($p)
	{
		global $tpl;
		$op = '';
		$t1 = $this->execTime();
		$time = isset($p['time'])?$p['time']:0;
		$len = isset($p['len'])?$p['len']:0;
		$len = $len == 0 ? $this->totalfile('../data/cache/'):$len;
		$f = isset($p['f']) ? $p['f'] : 1;
		$dv = ceil( ($f / $len) * 100 ) * 2;
		$fname = '../data/cache/'.md5($f).'.cache';
		$file = @require ($fname);
		foreach($file as $k => $v)
		{
			$cid = $this->GetField('class','cid',$v[4]);
			$arr['cid'] = $cid;
			$arr['fid'] = 0;
			$arr['pid'] = $v[0];
			$arr['title'] = $v[1];
			$arr['litpic'] = $v[2];
			$arr['piclist'] = $v[2];
			$arr['price'] = $v[6] * 100;
			$arr['volume'] = $v[7];
			$arr['percent'] = $v[8] * 100;
			$arr['money'] = $v[9] * 100;
			$arr['seller'] = $v[11];
			$arr['store'] = $v[12];
			$arr['contact'] = $v[10];
			$arr['platform'] = $v[13] == '天猫' ? 'tm' : 'tb';
			$arr['infourl'] = $v[3];
			$arr['taokeurl'] = $v[5];
			$arr['coupon'] = $v[14];
			$arr['maxtotal'] = $v[15];
			$arr['mintotal'] = $v[16];
			$arr['discount'] = $v[17];
			$arr['acturl'] = $v[20];
			$arr['actpath'] = $v[21];
			$arr['keyword'] = $v[1];
			$arr['keydesc'] = $v[1];
			$arr['sdatetimes'] = strtotime($v[18]);
			$arr['edatetimes'] = strtotime($v[19]);
			$arr['udatetimes'] = time();
			if($v[6] <= 20)
				$op = 'promotion';
			else if($v[8] > 50)
				$op = 'activity';
			else
				$op = 'coupon';
			$this->updateInfo($op,$arr,$v[0]);
		}
		@unlink($fname);
		$t2 = $this->execTime();
		$t2 = $t2 - $t1;
		$time += $t2;
		$tp = "<div style='width:200px;height:18px;border:1px solid #15428B;text-align:left'><div style='width:".$dv."px;height:18px;background:#2583c9'></div></div>";
		$tpk = $tp. "<br/>本次用时：<b style='color:red'>".$t2."</b> 秒，总用时：<b style='color:red'>".$time."</b> 秒，到达位置" .$f."，当前批次处理成功：继续执行任务...";
		if($f < $len)
		{
			$tpk = $tp. "<br/>本次用时：<b style='color:red'>".number_format($t2,8)."</b> 秒，总用时：<b style='color:red'>".number_format($time,2)."</b> 秒，到达位置 <b style='color:green'> " .$f."</b>，当前批次处理成功：继续执行任务...";
			$this->showmsg($tpk,'handle.php?m=importv&time='.($time + 0.1).'&len='.$len.'&f='.($f + 1),0,100);
		}
		else
		{
			$tpk = $tp. "<br />完成所有任务！，处理项目：<b style='color:red'>{$len} </b>总用时：<b style='color:red'>".number_format($time,2)."</b> 秒。";
			$this->showmsg($tpk,0);
		}
			
	}
	function nullOfEmpty()
	{
		$this->msg['statusCode'] = 300;
		$this->msg['message'] = '无权操作，访问拒绝';
		$this->msg['navTabId'] = '';
		$this->msg['callbackType'] = '';		
		$this->msg['rel'] = '';
		$this->msg['url'] = '';
		echo json_encode($this->msg);
	}
}
?>